#include <iostream>

// 饿汉模式 -- 以空间换取时间，初始化成本较高，但线程安全
class Singleton_H
{
public:
    static Singleton_H& getInstance()
    {
        return instance;
    }

    int getValue() const
    {
        return val;
    }

private:
    Singleton_H(): val(100) { std::cout << "Singleton_H 创建" << std::endl; }
    Singleton_H(const Singleton_H&) = delete;
    Singleton_H& operator=(const Singleton_H&) = delete;
    ~Singleton_H() {}

    static Singleton_H instance;
private:
    int val;
};
Singleton_H Singleton_H::instance;

// 懒汉模式 -- 懒加载，延迟初始化
// c++11 引入了局部静态变量的 thread safe 实现，可以实现线程安全的懒汉模式
class Singleton_L
{
public:
    static Singleton_L& getInstance()
    {
        static Singleton_L instance;
        return instance;
    }

    int getValue() const
    {
        return val;
    }
private:
    Singleton_L(): val(100) { std::cout << "Singleton_L 创建" << std::endl; }
    Singleton_L(const Singleton_L&) = delete;
    Singleton_L& operator=(const Singleton_L&) = delete;
    ~Singleton_L() {}
private:
    int val;
};


int main()
{
    // 调用 getInstance() 时，将懒汉模式放在前面，依然饿汉先初始化对象
    std::cout << "Singleton_L: " << Singleton_L::getInstance().getValue() << std::endl;
    std::cout << "Singleton_H: " << Singleton_H::getInstance().getValue() << std::endl;
    return 0;
}